<template>
  <div class="life-layout">
    <div class="life-title">
      <h2 class="life-title-txt">生活号</h2>
    </div>
    <div class="content-header">
      <Form ref="lifeForm" class="lifeForm" :model="form" :label-width="115">
        <Row>
          <Col span="12">
            <div class="content-header-box">
              <h3>生活号基本配置</h3>
            </div>
            <div class="content-box">
              <Form-item prop="title" label="生活号名称：">
                <Input v-model="form.title"></Input>
              </Form-item>
              <Form-item label="头像设置：">
                <div class="photobox">
                  <div class="demo-upload-list" v-show="form.headImgPath !== null">
                    <img :src="form.headImgPath">
                  </div>
                  <div class="photoUpload">
                    <Icon type="android-person-add" size="90" style="line-height: 180px"></Icon>
                    <input type="file" @change="photoUploadChange" ref="photoUpload" class="file">
                  </div>
                </div>
                <div class="tip"><span>一个月内只能修改一次，建议尺寸320×320px，支持jpg/jpeg/png格式，小于1M</span></div>
              </Form-item>
              <Form-item label="背景头像设置：">
                <div class="photobox" style="width: 288px;">
                  <div class="demo-upload-list" style="width: 288px" v-show="form.backgroundImgPath !== null">
                    <img :src="form.backgroundImgPath">
                  </div>
                  <div class="bgUpload">
                    <Icon type="image" size="90" style="line-height: 180px"></Icon>
                    <input type="file" @change="bgUploadChange" ref="bgUpload" class="file">
                  </div>
                </div>
                <div class="tip"><span>尺寸1600×1000px,支持jpg/jpeg/png格式，小于1M</span></div>
              </Form-item>
              <Form-item prop="description" label="简介设置：">
                <Input v-model="form.description" type="textarea" :rows="5" placeholder="一个月内只能修改一次，简介的内容需与生活号提供的服务和内容保持一致，否则可能影响审核结果，审核通过后自动生效，请谨慎填写。"></Input>
              </Form-item>
            </div>
          </Col>
          <Col span="12">
            <div class="content-header-box">
              <h3>生活号功能菜单配置(功能菜单上限4个)</h3>
            </div>
            <div class="content-box">
              <Checkbox-group v-model="menu">
                <Checkbox v-for="(item, index) in form.menus" :key="index" :label="item.name" class="margin-bottom"><span>{{item.name}}</span></Checkbox>
              </Checkbox-group>
              <div>
                <Button type="ghost" icon="plus" class="add" @click="addFormShow = true" disabled>添加自定义菜单</Button>
                <Button type="ghost" icon="minus" class="minus" v-show="form.menus.length !== 0" @click="deleteFormShow = true" disabled>删除菜单</Button>
              </div>
            </div>
          </Col>
        </Row>
        <div class="operate">
          <Button type="ghost" @click="reset('lifeForm')">重置</Button>
          <Button type="primary" @click="submitForm('lifeForm')">保存</Button>
        </div>
      </Form>
    </div>
    <!--自定义菜单弹框-->
    <Modal class="model" v-model="addFormShow" width="500" @click="resetAddForm('addForm')">
      <h2 slot="header" class="model-title">添加自定义菜单</h2>
      <Form ref="addForm" :rules="addRules" :model="addForm" :label-width="106">
            <Form-item prop="name" label="菜单名称：">
              <Input v-model="addForm.name" placeholder="请填写菜单名称"></Input>
            </Form-item>
        <Form-item prop="url" label="链接：">
          <Input v-model="addForm.url" placeholder="请填写菜单链接"></Input>
        </Form-item>
      </Form>
      <div slot="footer" style="text-align: center;">
        <Button type="ghost" size="large" @click="resetAddForm('addForm')">取消</Button>
        <Button type="primary" size="large" @click="submitAddForm('addForm')">提交</Button>
      </div>
    </Modal>
    <!--删除菜单弹框-->
    <Modal class="model" v-model="deleteFormShow" width="500" @click="resetDeleteForm('deleteForm')">
      <h2 slot="header" class="model-title">删除菜单</h2>
      <Form ref="deleteForm" :rules="deleteRules" :model="deleteForm" label-position="top">
        <Form-item prop="deleteMenu" label="请勾选要删除的菜单">
          <Checkbox-group class="menuList" v-model="deleteForm.deleteMenu">
            <Checkbox v-for="(item, index) in form.menus" :key="index" :label="item.name" class="margin-bottom"><span>{{item.name}}</span></Checkbox>
          </Checkbox-group>
        </Form-item>
      </Form>
      <div slot="footer" style="text-align: center;">
        <Button type="ghost" size="large" @click="resetDeleteForm('deleteForm')">取消</Button>
        <Button type="primary" size="large" @click="submitDeleteForm('deleteForm')">提交</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  export default {
    data () {
      return {
        addFormShow: false,
        deleteFormShow: false,
        searchData: {
          alipayClientInfoId: ''
        },
        form: {
          lifeWinId: '',
          title: '',
          headImgPath: null, // 头像
          backgroundImgPath: null, // 背景图
          description: '',
          menus: []
        },
        menu: [], // 选中的checkbox的值
        rules: {
          title: [
            {required: true, message: '请填写生活号名称', trigger: 'blur'}
          ],
          description: [
            {required: true, message: '请填写简介', trigger: 'blur'}
          ]
        },
        addForm: {
          id: '',
          lifeWindowId: '',
          name: '',
          url: '',
          checked: false
        },
        addRules: {
          name: [
            {required: true, message: '请填写菜单名称', trigger: 'blur'}
          ],
          url: [
            {required: true, message: '请填写链接', trigger: 'blur'}
          ]
        },
        deleteForm: {
          deleteMenu: []
        },
        deleteRules: {
          deleteMenu: [
            {required: true, type: 'array', min: 1, message: '您没有选择要删除的菜单', trigger: 'blur'}
          ]
        }
      }
    },
    mounted () {
      this.result()
    },
    methods: {
      result () {
        // 查询
        let that = this
        let url = that.api.life.result
        that.searchData.alipayClientInfoId = localStorage.getItem('dataId') || '8'// 前置配置项id
        this.$axios.get(url, { params: that.searchData }).then((res) => {
          let code = res.data.msg.code
          let data = res.data.data
          res.data.data.lifeWinId = res.data.data.id
          console.log(data)
          if (code === '20000') {
            that.form = data === undefined ? that.form : data
          } else {
            that.$Message.error({content: '网络异常', duration: 5})
          }
        }).catch((err) => {
          if (err) throw err
          that.$Message.error({content: '网络异常', duration: 5})
        })
      },
      photoUploadChange () {
        var that = this
        let len = this.$refs.photoUpload.files.length
        if (len === 1) {
          let photoFile = this.$refs.photoUpload.files[0]
          console.log(photoFile)
          var reader = new FileReader()
          reader.readAsDataURL(photoFile)
          reader.onload = function () {
            that.form.headImgPath = this.result
          }
        } else {
          that.form.headImgPath = null
        }
      },
      bgUploadChange () {
        var that = this
        let len = this.$refs.bgUpload.files.length
        if (len === 1) {
          let bgFile = this.$refs.bgUpload.files[0]
          console.log(bgFile)
          var reader = new FileReader()
          reader.readAsDataURL(bgFile)
          reader.onload = function () {
            that.form.backgroundImgPath = this.result
          }
        } else {
          that.form.backgroundImgPath = null
        }
      },
      submitForm (formName) {
        // 提交form
        let that = this
        let url = that.api.life.add
        that.form.alipayClientInfoId = localStorage.getItem('dataId') || '8'// 前置配置项id
        that.form.creatorId = localStorage.getItem('loginId')// 用户id
        for (var i = 0; i < that.menu.length; i++) {
          for (var j = 0; j < that.form.menus.length; j++) {
            if (that.menu[i] === that.form.menus[j].name) {
              that.form.menus[j].checked = true
            } else {
              that.form.menus[j].checked = false
            }
          }
        }
        let menuStr = JSON.stringify(that.form.menus)
        that.$refs[formName].validate((valid) => {
          if (valid) { // 通过验证
            let photoFileVal = that.$refs.photoUpload.value
            let bgFileVal = that.$refs.bgUpload.value
            if (photoFileVal === '') { // 如果未上传文件阻止提交
              that.$message({type: 'error', message: '请先上传头像图片'})
              return false
            }
            if (bgFileVal === '') { // 如果未上传文件阻止提交
              that.$message({type: 'error', message: '请先上传背景图片'})
              return false
            }
            that.$Modal.confirm({
              title: '提示',
              content: '是否继续?',
              onOk: () => {
                let formData = new FormData()
                formData.append('lifeWinId', that.form.lifeWinId)
                formData.append('title', that.form.title)
                formData.append('creatorId', that.form.creatorId)
                formData.append('description', that.form.description)
                formData.append('alipayClientInfoId', that.form.alipayClientInfoId)
                formData.append('menuArray', menuStr)
                formData.append('headImg', that.$refs.photoUpload.files[0])
                formData.append('backgroundImg', that.$refs.bgUpload.files[0])
                that.$axios.post(url, formData, {header: {'Content-Type': 'multipart/form-data'}}).then((res) => {
                  let code = res.data.msg.code
                  if (that.form.lifeWinId) {
                    // 修改
                    if (code === '20000') {
                      that.$Message.info({content: '修改成功', duration: 5})
                    } else {
                      that.$Message.error({content: '网络异常', duration: 5})
                    }
                  } else {
                    // 新增
                    if (code === '20000') {
                      res.data.data.lifeWinId = res.data.data.id
                      that.form = res.data.data
                      for (var j = 0; j < that.form.menus.length; j++) {
                        if (that.form.menus[j].checked === 1) {
                          that.menu.push(that.form.menus[j].name)
                        }
                      }
                      console.log(that.form)
                      that.$Message.info({content: '新增成功', duration: 5})
                    } else {
                      that.$Message.error({content: '网络异常', duration: 5})
                    }
                  }
                }).catch((err) => {
                  if (err) throw err
                  that.$Message.error({content: '网络异常', duration: 5})
                })
              },
              onCancel: () => {}
            })
          } else { // 未通过验证
            console.log('error')
          }
        })
      },
      reset (formName) {
        this.$refs[formName].lifeWinId = ''
        this.$refs[formName].title = ''
        this.$refs[formName].headImgPath = null
        this.$refs[formName].backgroundImgPath = null
        this.$refs[formName].description = ''
        this.menu = []
      },
      resetAddForm (formName) {
        this.$refs[formName].resetFields()
        this.addFormShow = false
      },
      submitAddForm (formName) {
        // 提交自定义菜单form
        let that = this
        that.$refs[formName].validate((valid) => {
          if (valid) { // 通过验证
            that.$Modal.confirm({
              title: '提示',
              content: '是否继续?',
              onOk: () => {
                var object = {}
                for (var key in that.addForm) {
                  object[key] = that.addForm[key]
                }
                that.form.menus.push(object)
                console.log(object)
                that.addFormShow = false
                that.$Message.info({content: '新增成功', duration: 5})
              },
              onCancel: () => {}
            })
          } else { // 未通过验证
            console.log('error')
          }
        })
      },
      resetDeleteForm (formName) {
        this.$refs[formName].deleteMenu = []
        this.deleteFormShow = false
      },
      submitDeleteForm (formName) {
        // 提交删除菜单form
        let that = this
        let url = that.api.life.deleteMenu
        that.$refs[formName].validate((valid) => {
          if (valid) { // 通过验证
            that.$Modal.confirm({
              title: '提示',
              content: '是否继续?',
              onOk: () => {
                let menuArr = []
                // 删除之缓存到本地的菜单,并且获取已经存到数据库的待删除的菜单
                for (var i = 0; i < that.deleteForm.deleteMenu.length; i++) {
                  for (var j = 0; j < that.form.menus.length; j++) {
                    if (that.form.menus[j].name === that.deleteForm.deleteMenu[i] && that.form.menus[j].id === '') {
                      // 将删除的值剔除
                      that.menu = that.menu.filter(function (item) {
                        return item !== that.form.menus[j].name
                      })
                      that.deleteForm.deleteMenu.splice(i, 1)
                      that.form.menus.splice(j, 1)
                    } else if (that.form.menus[j].name === that.deleteForm.deleteMenu[i] && that.form.menus[j].id !== '') {
                      // 已经存到数据库的待删除的菜单
                      menuArr.push(that.form.menus[j].id)
                    }
                  }
                }
                // 如果要删除的菜单没有已经存到数据库的，就不调用删除请求
                if (menuArr.length === 0) {
                  return false
                }
                // 删除已经存到数据库的菜单
                let object = {}
                object.id = JSON.stringify(menuArr)
                that.$axios.post(url, object).then((res) => {
                  let code = res.data.msg.code
                  if (code === '20000') {
                    for (var i = 0; i < menuArr.length; i++) {
                      for (var j = 0; j < that.form.menus.length; j++) {
                        if (menuArr[i] === that.form.menus[j].id) {
                          that.deleteForm.deleteMenu = that.deleteForm.deleteMenu.filter(function (item) {
                            return item !== that.form.menus[j].name
                          })
                          that.menu = that.menu.filter(function (item) {
                            return item !== that.form.menus[j].name
                          })
                          that.form.menus.splice(j, 1)
                        }
                      }
                    }
                    that.deleteFormShow = false
                    that.$Message.info({content: '删除成功', duration: 5})
                    console.log(that.form)
                  } else {
                    that.deleteFormShow = false
                    that.$Message.error({content: '网络异常', duration: 5})
                  }
                }).catch((err) => {
                  if (err) throw err
                  that.deleteFormShow = false
                  that.$Message.error({content: '网络异常', duration: 5})
                })
              },
              onCancel: () => {}
            })
          } else { // 未通过验证
            console.log('error')
          }
        })
      }
    }
  }
</script>
